#!/usr/bin/env bash

echo Manage services

dev_mode=true
if [ "$(echo "$*" | grep production | wc -l)" -eq 1 ]; then
  dev_mode=false
  echo We are in production
fi

profile=env-prod
if test "$dev_mode" = true; then
  profile=env-dev
  echo Dev mode. Do all the best!!!
fi

function wait-gwt() {
  echo wait for log file of "$1" at time "$(date +'%Y.%m.%d %H:%M:%S')"
  while [ ! -f "$1"/target/codeserver.log ]; do sleep 1; done
  while ! grep -q 'The code server is ready at' <(tail -f "$1"/target/codeserver.log); do sleep 1; done
  echo log file of "$1" is appears at time "$(date +'%Y.%m.%d %H:%M:%S')"
}

function gwt() {
  echo "Start $1"
  cd "$1" || echo "$1" not found || exit 1
  mvn gwt:codeserver &> target/codeserver.log
}

function systemProperty() {
  xmllint --xpath "string(//SystemProperty[@name = '$1']/@default)" main-server/src/main/jettyconf/context.xml
}

function initDB() {
    echo Init PostgreSQL database pooller
    podman run -dt --name pooller \
      -e POSTGRES_USER=$(systemProperty pg.user) \
      -e POSTGRES_PASSWORD=$(systemProperty pg.password) \
      -e POSTGRES_DB=$(systemProperty pg.user) \
      -p 15432:5432 \
      library/postgres
}

function startMail() {
  podman run -dt --name poolermail -p 18025:8025 -p $(systemProperty mail.smtp.port):1025 mailhog/mailhog
}

function jetty() {
    cd main-server || echo main-server not found || exit 1
    if test "$dev_mode" = true; then
      mvn jetty:run -P $profile
    else
      mvn jetty:run-war -P $profile
    fi
}

function stop() {
    if test "$dev_mode" = true; then
      echo Kill CodeServer
      ps aux | grep java | grep CodeServer | awk '{print $2}' | xargs kill -9
      echo Kill mail container
      podman container stop poolermail
      podman container rm poolermail
    fi
    echo Kill Jetty
    ps aux | grep java | grep jetty | awk '{print $2}' | xargs kill -9
    echo Remove database container
    podman container stop pooller
    podman container rm pooller
}

function start() {
    echo Compile...
    rm -rf target
    mkdir target
    mvn -P $profile clean compile install # &> target/compile.log
    if test "$dev_mode" = true; then
      gwt main-client &
      gwt maker-client &
      gwt landing &
      wait-gwt main-client && wait-gwt maker-client && wait-gwt landing
      startMail || stop
    fi
    initDB || stop
    jetty &
    P4=$!
    wait $P4
    stop
}

case $1 in
start) start;;
stop) stop;;
*)
  echo no value;;
esac
